<?php
namespace biu;


use biu\lib\Conf;
use biu\lib\Log;

class Biu{

    protected $config;

    /**
     * Biu constructor.
     */
    public function __construct()
    {

        define('HOME',dirname(__DIR__).DIRECTORY_SEPARATOR);
        #die(HOME);
        require HOME.'vendor/autoload.php';
        spl_autoload_register(function ($class){
            #echo $class;die;
            require HOME.str_replace('\\','/',$class).'.php';
        });

        $this->config = new Conf();

        set_error_handler([\biu\handler\Error::class,'error']); // 将所有php的错误转为异常
        #set_exception_handler([\biu\handler\Error::class,'exception']);   // 由用户自己处理异常

        register_shutdown_function([$this,'shutdown'],$this);


    }

    private function shutdown(self $biu){

        Log::flush();
    }


    public function bootstrap(){

        try {

            'cli' == PHP_SAPI ? self::cli() : self::web();
        }catch (\Exception $e){
            $str =  $e->getTraceAsString();

        } finally {
            Log::err($str,'error');

        }


    }

    /**
     * php biu.php curl/test1 aaa bbb
     *
     * print_r($GLOBALS['argv']);
     *Array
    (
    [0] => biu.php
    [1] => curl/test1
    [2] => aaa
    [3] => bbb
    )

     *
     *
     */
    private function cli(){
        define('PROJECT','console');
        #print_r($GLOBALS['argv']);
        #list($controller,$action) = explode('/',$GLOBALS['argv'][1]);
        #print_r($this->parsePath($GLOBALS['argv'][1]));die;
        $path = $this->parsePath($GLOBALS['argv'][1]);

        $controller = 'console\controller\\'.$path['c'];

        array_shift($GLOBALS['argv']);
        array_shift($GLOBALS['argv']);


        $C = new $controller;
        $re = new \ReflectionClass($C);
        $docs = $re->getMethod($path['a'])->getDocComment();



        #print_r(explode("\n",$docs));

        call_user_func_array([new $controller,$path['a']],$GLOBALS['argv']);


        #var_dump(ini_get('register_argc_argv'));
    }
    private function web(){
        $this->sapi = 'cgi';

        #print_r($_SERVER['REQUEST_URI']);die;

        $path = $this->parsePath(ltrim($_SERVER['REQUEST_URI'],'/') ?: 'index/index'  );

        $dirs = explode(DIRECTORY_SEPARATOR,$_SERVER['DOCUMENT_ROOT']);

        #print_r($dirs[count($dirs)-2]);die;
        define('PROJECT',$dirs[count($dirs)-2]);
        $controller = PROJECT.'\controller\\'.$path['c'];

        // 传递命名参数
        call_user_func_array([new $controller,$path['a']],[]);
    }

    /**
     * @param $path string curl-test/get-baidu
     * @return array ['c'=>'Controller','a'=>'Action']
     */
    private function parsePath($path){

        list($controller,$action) = explode('/',$path);

        return [
            'c'=>str_replace('-','',ucwords($controller,'-')).'Controller',
            'a'=>'action'.str_replace('-','',ucwords($action,'-'))
        ];
    }

}

